package com.tyust.web;


import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tyust.entity.Car;
import com.tyust.pager.PageBean;
import com.tyust.service.CarService;

@Controller
@RequestMapping("/car")
public class CarController {
	@Autowired
	private CarService carService;
	
	@RequestMapping("/load.do")
	public String load(String carNo,ModelMap map){
		Car car = carService.load(carNo);
		map.addAttribute("car", car);
		return "/jsps/car/desc";
	}
	
	private int getPc(HttpServletRequest request){
		int pc = 1;
		String param = request.getParameter("pc");
		if(param!=null && !param.trim().isEmpty()){
			try{
				pc = Integer.parseInt(param);
			}catch(RuntimeException e){ }
		}
		return pc;
	}
	
	private String getUrl(HttpServletRequest request){
		String url = request.getRequestURI()+"?"+request.getQueryString();
		int index = url.lastIndexOf("&pc=");
		if(index!=-1){
			url = url.substring(0, index);
		}
		return url;
	}
	
	@RequestMapping("/findByCondition.do")
	public String findByCondition(HttpServletRequest request,Car car){
		int pc = getPc(request);
		String url = getUrl(request);
		PageBean<Car> pb = carService.findByCondition(car, pc);
		pb.setUrl(url);
		request.setAttribute("pb", pb);
		return "/jsps/car/list";
	}
	
	
	@RequestMapping("/findByManufacturer.do")
	public String findByPress(HttpServletRequest request){
		int pc = getPc(request);
		String url = getUrl(request);
		String manufacturer = request.getParameter("manufacturer");
		Car car=new Car();
		car.setBname(manufacturer);
		PageBean<Car> pb = carService.findByCondition(car, pc);
		pb.setUrl(url);
		request.setAttribute("pb", pb);
		return "/jsps/car/list";
	}
	
	@RequestMapping("/findByBrand.do")
	public String findByBname(HttpServletRequest request){
		int pc = getPc(request);
		String url = getUrl(request);
		String brand = request.getParameter("brand");
		Car car=new Car();
		car.setBname(brand);
		PageBean<Car> pb = carService.findByCondition(car, pc);
		pb.setUrl(url);
		request.setAttribute("pb", pb);
		return "/jsps/car/list";
	}
	
}
